package com.ruoyi.quartz.task;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.SysLeave;
import com.ruoyi.system.service.ISysLeaveService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 老人请假状态更新任务
 * 
 * @author ruoyi
 */
@Component("elderLeaveTask")
public class ElderLeaveTask
{
    private static final Logger log = LoggerFactory.getLogger(ElderLeaveTask.class);

    @Autowired
    private ISysLeaveService leaveService;

    @Autowired
    private ISysUserService userService;

    /**
     * 更新老人请假状态
     */
    public void updateElderLeaveStatus()
    {
        log.info("开始执行老人请假状态更新任务 - {}", new Date());
        
        // 查询所有已通过且未结束的请假记录
        SysLeave query = new SysLeave();
        // 已通过
        query.setStatus("1");
        List<SysLeave> leaveList = leaveService.selectSysLeaveList(query);
        
        log.info("查询到{}条已通过的请假记录", leaveList.size());

        Date now = new Date();
        for (SysLeave leave : leaveList)
        {
            // 如果当前时间在请假时间范围内，更新老人状态为请假中
            if (now.after(leave.getStartTime()) && now.before(leave.getEndTime()))
            {
                SysUser elder = userService.selectUserById(leave.getElderUserId());
                if (elder != null)
                {
                    // 请假中
                    elder.setLeaveStatus("1");
                    userService.updateUser(elder);
                    log.info("请假老人", elder.getNickName());
                }
            }
            // 如果请假已结束，恢复老人状态为在院
            else if (now.after(leave.getEndTime()))
            {
                SysUser elder = userService.selectUserById(leave.getElderUserId());
                if (elder != null)
                {
                    // 在院
                    elder.setLeaveStatus("0");
                    userService.updateUser(elder);
                    log.info("出院老人", elder.getNickName());
                }
            }
        }
    }
} 